package com.ruoyi.common.utils.alipay.utils;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.ruoyi.common.utils.alipay.AlipayConfig;
import com.ruoyi.common.utils.alipay.bean.AliReturnPayBean;
import com.ruoyi.common.utils.alipay.bean.OrderTest;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

/**
 * Description:支付宝支付接口
 * Date:2019/04/23 15:58
 */
@Slf4j
public class AliPayUtil {

	/**
	 * 支付宝支付
	 * @param orderTest  商品信息包含回调地址
	 * @return String
	 */
	public static String alipay(OrderTest orderTest) {
		//获得初始化的AlipayClient
		//实例化客户端（参数：网关地址、商户appid、商户私钥、格式、编码、支付宝公钥、加密类型），为了取得预付订单信息
		AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID,
				AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET,
				AlipayConfig.ALIPAY_PUBLIC_KEY,AlipayConfig.SIGNTYPE);
		//设置请求参数
		//支付宝App支付接口
		AlipayTradeAppPayRequest alipayRequest = new AlipayTradeAppPayRequest();
		//设置页面跳转同步通知页面路径
		alipayRequest.setReturnUrl(orderTest.getReturnUrl());
		//设置回调地址，服务器异步通知页面路径
		alipayRequest.setNotifyUrl(orderTest.getNotifyUrl());
		AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
		model.setBody(orderTest.getBody());
		model.setSubject(orderTest.getSubjecy());
		model.setOutTradeNo(orderTest.getOutTradeNo());
		model.setTimeoutExpress("30m");
		model.setTotalAmount(orderTest.getTotalAmount());
		model.setProductCode("QUICK_MSECURITY_PAY");
		alipayRequest.setBizModel(model);
		try {
			AlipayTradeAppPayResponse response = alipayClient.sdkExecute(alipayRequest);
			if(response.isSuccess()){
				log.info("调用成功");
			}else{
				response.setMsg("error");
				log.info("调用失败");
			}
			String result = URLDecoder.decode(response.getBody(),"UTF-8");
			log.info("*********************\n返回结果为："+ result);
			return result;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 支付宝退款接口
	 * @param orderTest 商品信息
	 * @return
	 */
	public static String aliRefund(OrderTest orderTest) {
		//获得初始化的AlipayClient
		AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID,
				AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET,
				AlipayConfig.ALIPAY_PUBLIC_KEY,AlipayConfig.SIGNTYPE);
		//设置请求参数
		AlipayTradeAppPayRequest alipayRequest = new AlipayTradeAppPayRequest();
		//AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
		//设置页面跳转同步通知页面路径
		alipayRequest.setReturnUrl(orderTest.getReturnUrl());
		//设置回调地址，服务器异步通知页面路径
		alipayRequest.setNotifyUrl(orderTest.getNotifyUrl());
		try {
			alipayRequest.setBizContent("{\"out_trade_no\":\""+ orderTest.getOutTradeNo() +"\","
					+ "\"trade_no\":\""+ orderTest.getTradeNo() +"\","
					+ "\"refund_amount\":\""+ orderTest.getRefundAmount() +"\","
					+ "\"refund_reason\":\""+ orderTest.getRefundReason() +"\","
					+ "\"out_request_no\":\""+ orderTest.getOutRequestNo() +"\"}");
			//请求
			String result;

			//请求
			result = alipayClient.execute(alipayRequest).getBody();
			return result;
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 支付宝的验签方法
	 * @param req
	 * @return
	 */
	public static boolean checkSign(HttpServletRequest req) {
		Map<String, String[]> requestMap = req.getParameterMap();
		Map<String, String> paramsMap = new HashMap<>();
		requestMap.forEach((key, values) -> {
			String strs = "";
			for(String value : values) {
				strs = strs + value;
			}
			log.info(("key值为"+key+"value为："+strs));
			paramsMap.put(key, strs);
		});
		//调用SDK验证签名
		try {
			return  AlipaySignature.rsaCheckV1(paramsMap, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, AlipayConfig.SIGNTYPE);
		} catch (AlipayApiException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			log.info("*********************验签失败********************");
			return false;
		}
	}

	/**
	 * 支付宝回调的接口
	 * @param returnPay 支付宝返回数据用实体bean接收
	 * @return boolean
	 * @throws IOException
	 */
	public static boolean returnPay(HttpServletRequest req, AliReturnPayBean returnPay, HttpServletResponse response) throws IOException {
		boolean flag = false;
		if (!AliPayUtil.checkSign(req)) {
			return flag;
		}
		if (returnPay == null) {
			log.info("支付宝的returnPay返回为空");
			flag = true;
			return flag;
		}
		log.info("支付宝的returnPay" + returnPay.toString());
		//成功返回 TRADE_SUCCESS
		if ("TRADE_SUCCESS".equals(returnPay.getTrade_status())) {
			flag = true;
			log.info("支付宝的支付状态为TRADE_SUCCESS");
		}
		return flag;
	}

	public static void main(String[] args) {
		OrderTest orderTest = new OrderTest();
		orderTest.setBody("测试");
		orderTest.setOutTradeNo("1234");
		orderTest.setTotalAmount("0.01");
		orderTest.setSubjecy("鞋垫");
		AliPayUtil.alipay(orderTest);
		//logger.info(AliPayUtil.alipay(orderTest));
	}
}
